package org.example.leetCode.simple;


import java.util.Arrays;

/**
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class MergeTwoLists {

    public static void main(String[] args) {
        int[] arrNode1 = {1, 2, 4};
        int[] arrNode2 = {1, 3, 4};
        ListNode listNode1 = ListNode.generateNode(arrNode1);
        ListNode listNode2 = ListNode.generateNode(arrNode2);
        ListNode listNode = mergeTwoLists(listNode1, listNode2);
        int[] ints = ListNode.nodeToArray(listNode);
        System.out.println(Arrays.toString(ints));


    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        int length = l1.size+ l2.size;
        ListNode startNode = null;
        ListNode cur = null;
        if (l1.val < l2.val) {
            startNode = l1;
            cur = l1;
            l1 = l1.next;
        } else {
            startNode = l2;
            cur = l2;
            l2 = l2.next;
        }
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) {
            cur.next = l1;
        } else {
            cur.next = l2;
        }
        startNode.size = length;
        return startNode;
    }


    public static class ListNode {
        int val;
        ListNode next;
        int size = 0;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
            size++;
        }

        public static ListNode generateNode(int[] arr) {
            ListNode head = new ListNode(arr[0]);
            ListNode cur = head;
            head.size++;
            for (int i = 1; i < arr.length; i++) {
                cur.next = new ListNode(arr[i]);
                cur = cur.next;
                head.size++;
            }
            return head;
        }

        public static int[] nodeToArray(ListNode node) {
            ListNode temp = node;
            int[] arr = new int[temp.size];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = temp.val;
                temp = temp.next;
            }
            return arr;
        }
    }
}
